package com.qk.management.aop;

import cn.hutool.json.JSONUtil;
import com.qk.common.utils.CurrentUserContextHolders;
import com.qk.entity.OperateLog;
import com.qk.management.mapper.OperateLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/*
 *  @author SHCJ
 *  @created 2025/10/17 19:49
 *  @description
 */
@Slf4j
@Aspect
@Component
public class OperateLogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Pointcut("@annotation(com.qk.management.aop.ann.LogAnn)")
    public void pointcut() {}

    @Around("pointcut()")
    public Object Log(ProceedingJoinPoint pjp){

        Long start = System.currentTimeMillis();
        log.info("开始:{}",start);
        Object proceed = null;
        try {
            proceed = pjp.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        Long end =System.currentTimeMillis() ;
        log.info("结束:{}",end);
        operateLogMapper.insert(OperateLog.builder()
                .operateUserId(CurrentUserContextHolders.get())
                .operateTime(LocalDateTime.now())
                .className(pjp.getTarget().getClass().getName())
                .methodName(pjp.getSignature().getName())
                .methodParams(JSONUtil.toJsonStr(pjp.getArgs()))
                .returnValue(JSONUtil.toJsonStr(proceed))
                .costTime(end-start)
                .build());

        return proceed;


    }
}
